package cn.jsj.onclock.controller;

import cn.jsj.onclock.exception.CustomException;
import cn.jsj.onclock.interceptor.swich.PassToken;
import cn.jsj.onclock.management.ExcelWorkBookFactory;
import cn.jsj.onclock.pojo.SignEnt;
import cn.jsj.onclock.pojo.TaskEnt;
import cn.jsj.onclock.pojo.identity.UserIdentityEnum;
import cn.jsj.onclock.result.Result;
import cn.jsj.onclock.service.SignService;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;

import static cn.jsj.onclock.interceptor.RequestThreadContext.requesterIdentity;
import static cn.jsj.onclock.interceptor.RequestThreadContext.requesterUserId;

/**
 * @author 卢斌
 */
@CrossOrigin
@Controller
@ResponseBody
@RequestMapping(value = "/sign")
public class SignController {

    private final SignService signService;

    private final ExcelWorkBookFactory excelWorkBookFactory;

    @Autowired
    public SignController(SignService signService, ExcelWorkBookFactory excelWorkBookFactory) {
        this.signService = signService;
        this.excelWorkBookFactory = excelWorkBookFactory;
    }

    /**
     * 群相关负责人主动发起一次签到
     */
    @PostMapping(value = "/sign")
    public Result<Long> sign(@RequestBody SignEnt signEnt) {
        Long creatorId = requesterUserId();
        Long signId = signService.addOneSign(creatorId, signEnt.getAimGroup(), signEnt.getStartTime(), signEnt.getLimitTime(), signEnt.getTitle(), signEnt.getLabelId(), signEnt.getAimUserIdList());
        return Result.success(signId);
    }


    /**
     * 查询用户发起的签到列表（详细）
     */
    @GetMapping(value = "/user_sign", params = {"pageNum", "pageSize"})
    public Result<SignEnt> userIssue(@RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize) {
        Long userId = requesterUserId();
        List<SignEnt> storage = signService.listSignEntOfIssuedFromUser(userId, pageNum, pageSize);
        return Result.success(storage);
    }


    /**
     * 查询用户在某一群组中的发起签到记录
     */
    @GetMapping(value = "/user_sign_record_group", params = {"groupId", "startTime", "untilTime", "pageNum", "pageSize"})
    public Result<SignEnt> userIssueDetailRecord(Long groupId, Date startTime, Date untilTime, Integer pageNum, Integer pageSize) {
        Long userId = requesterUserId();
        List<SignEnt> storage = signService.listSignRecord(userId, groupId, startTime, untilTime, pageNum, pageSize);
        return Result.success(storage);
    }


    /**
     * 查询用户相关的签到任务实体（详细）
     */
    @GetMapping(value = "/user_task", params = {"pageNum", "pageSize"})
    public Result<TaskEnt> userAboutTask(@RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize) {
        Long userId = requesterUserId();
        List<TaskEnt> storage = signService.listExecutorTask(userId, pageNum, pageSize);
        return Result.success(storage);
    }


    /**
     * 用户查看某一签到的完成进度（用户仅仅可以看到自己发起的签到）
     */
    @GetMapping(value = "/finish_process", params = {"signId"})
    public Result<TaskEnt> finishProcess(@RequestParam("signId") Long signId) {
        Long userId = requesterUserId();
        UserIdentityEnum userIdentityEnum = requesterIdentity();
        List<TaskEnt> storage = signService.listSignFinishProgress(userId, userIdentityEnum, signId);
        return Result.success(storage);
    }


    /**
     * 查询某一签到者在特定的几个签到中的完成情况
     */
    @GetMapping(value = "/executor_status", params = {"executor", "signIdList"})
    public Result<TaskEnt> checkExecutorSignFinishStatus(@RequestParam("executor") Long executor, @RequestParam("signIdList") List<Long> signIdList) {
        Long userId = requesterUserId();
        UserIdentityEnum userIdentity = requesterIdentity();
        List<TaskEnt> storage = signService.listExecutorFinishProgressInSpecialSign(userId, executor, signIdList, userIdentity);
        return Result.success(storage);
    }

    @PassToken
    @GetMapping(value = "/excel")
    public void getExe(HttpServletResponse response) {
        XSSFWorkbook xssfWorkbook = excelWorkBookFactory.getWorkbook();
        try {
            response.setHeader("Content-Disposition","attachment;filename=record.xlsx");
            OutputStream outputStream = response.getOutputStream();
            xssfWorkbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            throw new CustomException("有错误");
        }
    }


    /**
     * 群组内部分人员的签到信息Excel表格导出
     */
    @GetMapping(value = "/sign_info_dump", params = {"signIdList", "userIdList", "groupId"})
    public void dumpExcel(@RequestParam("signIdList") List<Long> signIdList, @RequestParam("userIdList") List<Long> userIdList, @RequestParam("groupId") Long groupId, HttpServletResponse response) {
        UserIdentityEnum userIdentityEnum = requesterIdentity();
        Long userId = requesterUserId();
        signService.clockRecordOutPutExcel(userId, userIdentityEnum, groupId, userIdList, signIdList, response);
    }


}
